package hhm.android.my

import android.os.Bundle
import android.os.Handler
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.LinearLayoutManager
import hhm.android.my.databinding.ActivityMessageListBinding
import siau.android.base.HttpHelper
import siau.android.base.SBBaseActivity
import siau.android.http.model.SystemMessageListModel
import siau.android.http.model.SystemMessageRequest
import siau.android.library.KeyString
import java.util.*

class MessageSystemListActivity : SBBaseActivity() {

    lateinit var dataBinding: ActivityMessageListBinding
    var list = ArrayList<SystemMessageListModel>()
    var pageNo = 1
    var pageSize = 10
    lateinit var adapter: MessageSystemListAdapter
    var dialogId = -1

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setTitleWhiteAndTextBlank()
        dataBinding = DataBindingUtil.setContentView(this, R.layout.activity_message_list)
        initTitle(getString(R.string.app_name))

        dialogId = intent.getIntExtra(KeyString.id, -1)

        dataBinding.activityMessageListRecycler.layoutManager = LinearLayoutManager(this)
        adapter = MessageSystemListAdapter(this, list)
        dataBinding.activityMessageListRecycler.adapter = adapter

        dataBinding.activityMessageListSrl.setOnRefreshListener {
            pageNo++
            getData()
        }
        dataBinding.activityMessageListSrl.setEnableLoadMore(false)

        showLoadingFragment(R.id.activity_message_list_fl)
        getData()
    }

    private fun getData() {
        val d = SystemMessageRequest(dialogId, pageNo, pageSize)
        HttpHelper().getSystemMessageList(d)?.subscribe({
            dataBinding.activityMessageListSrl.finishRefresh()
            removeLoadingFragment()
            if (pageNo == 1) {
                if (it.list.size == 0) {
                    showNoDataView()
                } else {
                    Collections.reverse(it.list)
                    adapter.setData(it.list)
                    dataBinding.activityMessageListRecycler.smoothScrollToPosition(adapter.list.size - 1)
                }
            } else {
                Collections.reverse(it.list)
                adapter.addData(0, it.list)
            }
//            if (adapter.list.size == it.total) {
//                Handler().postDelayed({
//                    dataBinding.activityMessageListSrl.setEnableRefresh(false)
//                }, 1000)
//            }
        }, {
            dataBinding.activityMessageListSrl.finishRefresh()
            removeLoadingFragment()
            showToast(it.message)
        })
    }
}